/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ipfw.cs590.cheat.struts.actions;

import edu.ipfw.cs590.cheat.AssignmentManagementInterface;
import edu.ipfw.cs590.cheat.AssignmentManagementService;
import edu.ipfw.cs590.cheat.Keyword;
import edu.ipfw.cs590.cheat.struts.ForwardParameters;
import edu.ipfw.cs590.cheat.struts.actionforms.AssignmentSearchForm;
import edu.ipfw.cs590.cheat.struts.actionforms.AssignmentSearchForm.SearchType;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.web_cat._1_0.assignment_sharing.Assignment;

/**
 *
 * @author SafarTimuro
 */
public class SearchAssignments extends Action {

    /* forward name="success" path="" */
    private final static String SUCCESS = "success";
    private final static String UUID_SUCCESS = "successUUID";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //If we have a valid form
        if (form instanceof AssignmentSearchForm) {
            AssignmentSearchForm asf = (AssignmentSearchForm) form;

            try {
                //Setup webservice
                AssignmentManagementService service = new AssignmentManagementService();
                AssignmentManagementInterface port = service.getAssignmentManagementSOAP();
                List<Assignment> searchResult = new ArrayList<Assignment>();

                // TODO sanitize input?
                String searchString = asf.getQuery();

                //Decide what search to run
                switch (SearchType.valueOf(asf.getSearchType())) {
                    case Course: //Course search
                        searchResult = port.findAssignmentByCourse(searchString);
                        break;
                    case Keyword: //Keyword search
                        //Create keyword list
                        StringTokenizer tok = new StringTokenizer(searchString);
                        List<Keyword> keywords = new ArrayList<Keyword>();

                        //Tokenize on white space and turn that into keywords
                        while (tok.hasMoreTokens()) {
                            Keyword cur = new Keyword();
                            cur.setKeyword(tok.nextToken());
                            keywords.add(cur);
                        }

                        //Search
                        searchResult = port.findAssignmentByKeyword(keywords);
                        break;
                    case Language: //Language search
                        searchResult = port.findAssignmentByLanguage(searchString);
                        break;
                    case UUID: //Search by UUID
                        try {
                            if (port.getAssignmentMetadata(asf.getQuery()) != null) {
                                //Forward to assignment page
                                return new ForwardParameters().add("id", asf.getQuery()).forward(mapping.findForward(UUID_SUCCESS));
                            }
                        } catch (Exception exc) {
                            asf.setSearchResults(searchResult);
                        }
                        return mapping.getInputForward();
                    default: //Unknown search type
                        ActionMessages errors = new ActionMessages();
                        errors.add("unsupportedSearch", new ActionMessage("errors.search.option.unsupported", asf.getSearchType()));
                        saveErrors(request, errors);
                        return new ActionForward(mapping.getInput());
                }

                //Successfull search
                asf.setSearchResults(searchResult);
                return mapping.findForward(SUCCESS);
            } catch (Exception exc) {
                //Something bad happened on the webservice side fail.
                ActionMessages errors = new ActionMessages();
                errors.add(ActionMessages.GLOBAL_MESSAGE,
                        new ActionMessage("errors.service.error", "Search Assignment", exc.getMessage()));
                this.saveErrors(request, errors);

                //Return failure.
                return mapping.getInputForward();
            }
        }

        //Something bad happened on the webservice side fail.
        ActionMessages errors = new ActionMessages();
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.form.invalid"));
        this.saveErrors(request, errors);

        return mapping.getInputForward();
    }
}
